package com.gxar.quick.ar.server.base.sdk;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.common.properties.IdentifyProperties;
import com.gxar.quick.ar.server.base.common.utils.FileUtils;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/12/26 09:46
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IdentifySDK {

    private final IdentifyProperties identifyProperties;

    /**
     * 添加识别图
     *
     * @param userId 用户id
     * @param workId 作品id
     * @param image  图片
     * @return 失败原因
     */
    public String addIdentify(Long userId, Long workId, String image) {
        String url = identifyProperties.getUrl() + "/v1/add_image";
        Map<String, String> addRequestBody = new HashMap<>();
        addRequestBody.put("path", userId.toString());
        addRequestBody.put("business_id", workId.toString());
        addRequestBody.put("limit_size", "false");
        addRequestBody.put("image_resize", "false");
        addRequestBody.put("multi_result", "true");
        addRequestBody.put("image_base64", FileUtils.getImageBase64(image));
        HttpResponse response = HttpUtil.createPost(url).body(JSON.toJSONString(addRequestBody), ContentType.JSON.getValue()).timeout(60000).execute();
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            addRequestBody.remove("image_base64");
            addRequestBody.put("image_url", image);
            log.error("识别图上传内部错误，请求信息：[{}]", JSON.toJSONString(addRequestBody));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR);
        }
        String responseBody = UnicodeUtil.toString(response.body());
        if (StringUtils.isBlank(responseBody)) {
            addRequestBody.remove("image_base64");
            addRequestBody.put("image_url", image);
            log.error("识别图上传失败：response为空，请求信息：[{}]", JSON.toJSONString(addRequestBody));
            return "fail";
        }
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String message = jsonObject.getString("msg");
        if (StringUtils.isNotBlank(message)) {
            boolean success = message.equals("入库成功");
            if (!success) {
                addRequestBody.remove("image_base64");
                addRequestBody.put("image_url", image);
                log.info("识别图上传失败，请求信息：[{}]，msg：[{}]", JSON.toJSONString(addRequestBody), message);
                return message;
            }
        } else {
            addRequestBody.remove("image_base64");
            addRequestBody.put("image_url", image);
            log.error("识别图上传失败，请求信息：[{}]，response：[{}]", JSON.toJSONString(addRequestBody), responseBody);
            return "fail";
        }
        return null;
    }

    /**
     * 删除识别图
     *
     * @param userId 用户id
     * @param workId 作品id
     * @param image  图片
     * @return 响应
     */
    public String delIdentify(Long userId, Long workId, String image) {
        String url = identifyProperties.getUrl() + "/v1/del_image";
        Map<String, String> delRequestBody = new HashMap<>();
        delRequestBody.put("path", userId.toString());
        delRequestBody.put("business_id", workId.toString());
        delRequestBody.put("limit_size", "false");
        delRequestBody.put("image_resize", "false");
        delRequestBody.put("multi_result", "true");
        delRequestBody.put("image_base64", FileUtils.getImageBase64(image));
        HttpResponse response = HttpUtil.createPost(url).body(JSON.toJSONString(delRequestBody), ContentType.JSON.getValue()).timeout(60000).execute();
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            delRequestBody.remove("image_base64");
            delRequestBody.put("image_url", image);
            log.error("识别图删除异常，请求信息：[{}]", JSON.toJSONString(delRequestBody));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_DEL_ERROR);
        }
        String responseBody = UnicodeUtil.toString(response.body());
        if (StringUtils.isBlank(responseBody)) {
            delRequestBody.remove("image_base64");
            delRequestBody.put("image_url", image);
            log.error("识别图删除失败：response为空，请求信息：[{}]", JSON.toJSONString(delRequestBody));
            return "fail";
        }
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String message = jsonObject.getString("msg");
        if (StringUtils.isNotBlank(message)) {
            boolean success = message.equals("success");
            if (!success) {
                delRequestBody.remove("image_base64");
                delRequestBody.put("image_url", image);
                log.info("识别图删除失败，请求信息：[{}]，msg：[{}]", JSON.toJSONString(delRequestBody), message);
                String notFound = "there are not math image";
                return message;
            }
        } else {
            delRequestBody.remove("image_base64");
            delRequestBody.put("image_url", image);
            log.error("识别图删除失败，请求信息：[{}]，response：[{}]", JSON.toJSONString(delRequestBody), responseBody);
            return "fail";
        }
        return null;
    }

    /**
     * 识别图清空
     *
     * @param userId 用户id
     * @return 失败信息
     */
    public String clearIdentify(Long userId) {
        String url = identifyProperties.getUrl() + "/v1/clear_image";
        Map<String, String> delRequestBody = new HashMap<>();
        delRequestBody.put("path", userId.toString());
        delRequestBody.put("limit_size", "false");
        delRequestBody.put("image_resize", "false");
        HttpResponse response = HttpUtil.createPost(url).body(JSON.toJSONString(delRequestBody), ContentType.JSON.getValue()).timeout(60000).execute();
        int status = response.getStatus();
        String responseBody = UnicodeUtil.toString(response.body());
        if (status == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            // 如果清空的时候报错500就是云端es没有该用户的索引
            JSONObject jsonObject = JSON.parseObject(responseBody);
            String message = jsonObject.getString("message");
            if ("Internal Server Error".equals(message)) {
                return null;
            } else {
                throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_DEL_ERROR);
            }
        }
        if (StringUtils.isBlank(responseBody)) {
            log.error("识别图清空失败：response为空，请求信息：[{}]", JSON.toJSONString(delRequestBody));
            return "fail";
        }
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String message = jsonObject.getString("msg");
        if (StringUtils.isNotBlank(message)) {
            boolean success = message.startsWith("/root/cache");
            if (!success) {
                log.error("识别图清空失败，请求信息：[{}]，msg：[{}]", JSON.toJSONString(delRequestBody), message);
                return message;
            }
        } else {
            log.error("识别图清空失败，请求信息：[{}]，response：[{}]", JSON.toJSONString(delRequestBody), responseBody);
            return "fail";
        }
        return null;
    }

    /**
     * 识别图识别
     *
     * @param userId      用户ID
     * @param workId      作品ID
     * @param image       图片
     * @param multiResult
     * @return 识别结果
     */
    public String predictIdentify(String version, Long userId, Long workId, String image, Boolean multiResult) {
        String url = identifyProperties.getUrl() + "/" + version + "/predict_image";
        Map<String, Object> predictRequest = new HashMap<>();
        predictRequest.put("path", userId.toString());
        predictRequest.put("business_id", workId.toString());
        predictRequest.put("limit_size", false);
        predictRequest.put("image_resize", false);
        predictRequest.put("multi_result", multiResult);
        predictRequest.put("image_base64", image);
        HttpResponse response = HttpUtil.createPost(url).body(JSON.toJSONString(predictRequest), ContentType.JSON.getValue()).timeout(60000).execute();
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            predictRequest.remove("image_base64");
            predictRequest.put("image_url", image);
            log.error("识别图识别内部错误，请求信息：[{}]", JSON.toJSONString(predictRequest));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR);
        }
        String responseBody = UnicodeUtil.toString(response.body());
        if (StringUtils.isBlank(responseBody)) {
            predictRequest.remove("image_base64");
            predictRequest.put("image_url", image);
            log.error("识别图识别失败：response为空，请求信息：[{}]", JSON.toJSONString(predictRequest));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR);
        }
//        if (responseBody.startsWith("{")) {
//            JSONObject jsonObject = JSON.parseObject(responseBody);
//            String message = jsonObject.getString("message");
//            if (StringUtils.isNotBlank(message)) {
//                predictRequest.remove("image_base64");
//                predictRequest.put("image_url", image);
//                log.info("识别图识别失败，请求信息：[{}]，msg：[{}]", JSON.toJSONString(predictRequest), message);
//                throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR.getRet(), message);
//            } else {
//                return responseBody;
//            }
//        } else {
//            return responseBody;
//        }
        return responseBody;
    }

    /**
     * 构建识别图索引
     *
     * @param userId 用户ID
     * @return 构建结果
     */
    public String buildIdentify(Long userId) {
        String url = identifyProperties.getUrl() + "/v1/build_index";
        Map<String, Object> predictRequest = new HashMap<>();
        predictRequest.put("path", userId.toString());
        HttpResponse response = HttpUtil.createPost(url).body(JSON.toJSONString(predictRequest), ContentType.JSON.getValue()).timeout(60000).execute();
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            log.error("构建识别图内部错误，请求信息：[{}]", JSON.toJSONString(predictRequest));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR);
        }
        String responseBody = UnicodeUtil.toString(response.body());
        if (StringUtils.isBlank(responseBody)) {
            log.error("构建识别图失败：response为空，请求信息：[{}]", JSON.toJSONString(predictRequest));
            throw new APIRuntimeException(ResultCodeEnum.WORK_IDENTIFY_UPLOAD_ERROR);
        }
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String message = jsonObject.getString("msg");
        if (StringUtils.isNotBlank(message)) {
            boolean success = message.equals("本地向量索引库重建成功");
            if (!success) {
                log.info("构建识别图失败，请求信息：[{}]，msg：[{}]", JSON.toJSONString(predictRequest), message);
                return message;
            }
        } else {
            log.error("构建识别图失败，请求信息：[{}]，response：[{}]", JSON.toJSONString(predictRequest), responseBody);
            return "fail";
        }
        return null;
    }
}
